package dao

import (
	"goadmin/model"

	"gorm.io/gorm"
)

func UserLikeUsername(username string) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		return db.Where("username like ?", "%"+username+"%")
	}
}

func UserLikeNickname(nickname string) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		return db.Where("nickname like ?", "%"+nickname+"%")
	}
}

func UserAuthLessThan(auth uint) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		return db.Where("auth < ?", auth)
	}
}

func GetUserByIdT[T any](id uint) (user T, err error) {
	err = db.Model(&model.User{}).Where("id = ?", id).First(&user).Error
	return
}

func GetUserById(id uint) (user model.User, err error) {
	user, err = GetUserByIdT[model.User](id)
	return
}

func GetUserByUsername(username string) (user model.User, err error) {
	err = db.Where(&model.User{Username: username}).First(&user).Error
	return
}

func GetUserList[T any](page, pageSize int, conditions ...Condition) (users []T, total int64, err error) {
	tx := db.Model(&model.User{})
	for _, condition := range conditions {
		tx = condition(tx)
	}
	err = tx.Scopes(paginate(page, pageSize)).Find(&users).Error
	if err != nil {
		return
	}
	err = tx.Count(&total).Error
	return
}

func InsertUser(user model.User) (err error) {
	err = db.Create(&user).Error
	return
}

func UpdateUserByUser(user model.User) (err error) {
	err = db.Save(&user).Error
	return
}

func DelUserById(id uint) (err error) {
	err = db.Delete(&model.User{}, id).Error
	return
}

func DelUserByIds(curAuth uint, ids []uint) (err error) {
	err = db.Where("id in (?)", ids).Where("auth < ?", curAuth).Delete(&model.User{}).Error
	return
}
